import { useEffect, useRef, useState } from 'react'
import { useMemoizedFn } from 'ahooks'
import dayjs from 'dayjs'
import copy from 'copy-to-clipboard'
import { Button, Card, DatePicker, message, Popover, Select } from 'antd'
import { CopyOutlined, EditOutlined } from '@ant-design/icons'

import { getShipFromName } from '../../utils'
import { apiGetAmazonInfo, apiUpdateCardInfo } from './apis'
import { IDeliveryDetails } from './interface'
import styles from './styles.module.less'

const { RangePicker } = DatePicker

interface IProps {
  waybillNo: string
}

/** 亚马逊卡片 */
export const Amazon = (props: IProps) => {
  const { waybillNo } = props
  const [amazonInfo, setAmazonInfo] = useState<IDeliveryDetails>({} as IDeliveryDetails)
  const [loading, setLoading] = useState<boolean>(false)
  const [predictDwFlag, setPredictDwFlag] = useState<boolean>(false)
  const [shipFromFlag, setShipFromFlag] = useState<boolean>(false)
  const [actualSignFlag, setActualSignFlag] = useState<boolean>(false)
  const infoRef = useRef<IDeliveryDetails>({} as IDeliveryDetails)

  // 请求接口
  const initData = useMemoizedFn(async (isinit?: boolean) => {
    try {
      if (isinit) setLoading(true)
      const data = await apiGetAmazonInfo(waybillNo)
      setAmazonInfo(data)
      infoRef.current = data
    } finally {
      if (isinit) setLoading(false)
    }
  })

  // 复制
  const copyHandler = useMemoizedFn((text: string | undefined) => {
    if (!text) return
    copy(`${text}`)
    message.success('复制成功', 1)
  })

  // 保存
  const onSaveHandler = useMemoizedFn(async key => {
    if (key === 'dw') {
      await apiUpdateCardInfo({
        waybillNo,
        practicalDeliveryTimeStart: infoRef.current.practicalDeliveryTimeStart,
        practicalDeliveryTimeEnd: infoRef.current.practicalDeliveryTimeEnd,
      })
      setPredictDwFlag(false)
    }
    if (key === 'shipFrom') {
      await apiUpdateCardInfo({
        waybillNo,
        shipFrom: infoRef.current.shipFrom,
      })
      setShipFromFlag(false)
    }
    if (key === 'practicalSignTime') {
      await apiUpdateCardInfo({ waybillNo, practicalSignTime: infoRef.current.practicalSignTime })
      setActualSignFlag(false)
    }
    initData()
  })

  useEffect(() => {
    initData(true)
  }, [initData, waybillNo])

  if (!amazonInfo?.fbaId) return null
  return (
    <Card className={styles.card} title="Amazon" loading={loading}>
      <div className={styles.box}>
        <div className={styles.contain}>
          <div className={styles.item}>
            <span className={styles.label}>FBA ID</span>
            <span>{amazonInfo?.fbaId}</span>
            <CopyOutlined
              className={styles.copyIcon}
              onClick={() => {
                copyHandler(amazonInfo?.fbaId)
              }}
            />
          </div>
          <div className={styles.item}>
            <span className={styles.label}>RE ID</span>
            <span>{amazonInfo?.reId}</span>
            <CopyOutlined
              className={styles.copyIcon}
              onClick={() => {
                copyHandler(amazonInfo?.reId)
              }}
            />
          </div>
          <div className={styles.item}>
            <span className={styles.label}>Delivery window(预计)</span>
            <span>
              {amazonInfo?.predictTimeStart && amazonInfo?.predictTimeEnd
                ? `${amazonInfo?.predictTimeStart} ~ ${amazonInfo?.predictTimeEnd}`
                : '-'}
            </span>
            <CopyOutlined
              className={styles.copyIcon}
              onClick={() => {
                copyHandler(`${amazonInfo?.predictTimeStart} ~ ${amazonInfo?.predictTimeEnd}`)
              }}
            />
          </div>
          <div className={styles.item}>
            <span className={styles.label}>Delivery window(实际)</span>
            <span>
              {amazonInfo?.practicalDeliveryTimeStart && amazonInfo?.practicalDeliveryTimeEnd
                ? `${amazonInfo?.practicalDeliveryTimeStart} ~ ${amazonInfo?.practicalDeliveryTimeEnd}`
                : '-'}
            </span>
            <Popover
              overlayInnerStyle={{ width: '400px' }}
              open={predictDwFlag}
              trigger="click"
              destroyTooltipOnHide={true}
              content={
                <div>
                  <div className={styles.flex}>
                    <span>DW(实际)</span>
                    <RangePicker
                      style={{ flex: '1 auto' }}
                      defaultValue={[
                        infoRef.current.practicalDeliveryTimeStart
                          ? dayjs(infoRef.current.practicalDeliveryTimeStart)
                          : null,
                        infoRef.current.practicalDeliveryTimeEnd
                          ? dayjs(infoRef.current.practicalDeliveryTimeEnd)
                          : null,
                      ]}
                      onChange={value => {
                        if (!value) return
                        infoRef.current.practicalDeliveryTimeStart = dayjs(value[0]).format($F_YMD)
                        infoRef.current.practicalDeliveryTimeEnd = dayjs(value[1]).format($F_YMD)
                      }}
                    />
                  </div>
                  <div className={styles.footer}>
                    <Button
                      onClick={() => {
                        setPredictDwFlag(false)
                        infoRef.current = amazonInfo
                      }}
                    >
                      取消
                    </Button>
                    <Button
                      type="primary"
                      onClick={() => {
                        onSaveHandler('dw')
                      }}
                    >
                      保存
                    </Button>
                  </div>
                </div>
              }
            >
              <EditOutlined
                className={styles.editIcon}
                onClick={() => {
                  setPredictDwFlag(true)
                }}
              />
            </Popover>
          </div>
          <div className={styles.item}>
            <span className={styles.label}>DW天数</span>
            <span>{amazonInfo?.dayNum}</span>
          </div>
          <div className={styles.item}>
            <span className={styles.label}>Ship From</span>
            <span>{getShipFromName(amazonInfo?.shipFrom)}</span>
            <Popover
              overlayInnerStyle={{ width: '400px' }}
              open={shipFromFlag}
              trigger="click"
              destroyTooltipOnHide={true}
              content={
                <div>
                  <div className={styles.flex}>
                    <span>Ship From</span>
                    <Select
                      defaultValue={amazonInfo?.shipFrom}
                      style={{ flex: '1 auto' }}
                      placeholder="请选择"
                      options={getShipFromName.valueList.map(v => ({
                        label: getShipFromName(v),
                        value: v,
                      }))}
                      onChange={value => {
                        infoRef.current.shipFrom = value
                        infoRef.current.dayNum = value === 1 ? '14' : '7'
                      }}
                    />
                  </div>
                  <div className={styles.footer}>
                    <Button
                      onClick={() => {
                        setShipFromFlag(false)
                        infoRef.current = amazonInfo
                      }}
                    >
                      取消
                    </Button>
                    <Button
                      type="primary"
                      onClick={() => {
                        onSaveHandler('shipFrom')
                      }}
                    >
                      保存
                    </Button>
                  </div>
                </div>
              }
            >
              <EditOutlined
                className={styles.editIcon}
                onClick={() => {
                  setShipFromFlag(true)
                }}
              />
            </Popover>
          </div>
          <div className={styles.item}>
            <span className={styles.label}>预计签收日期(初始)</span>
            <span>{amazonInfo?.predictSignTime || '-'}</span>
          </div>
          <div className={styles.item}>
            <span className={styles.label}>预计签收日期(动态)</span>
            <span>
              {amazonInfo?.dynamicSignTime || '-'}{' '}
              {amazonInfo?.predictSignTime && amazonInfo?.dynamicSignTime
                ? `(${dayjs(amazonInfo?.dynamicSignTime).diff(dayjs(amazonInfo?.predictSignTime), 'day')})`
                : ''}
            </span>
            <CopyOutlined
              className={styles.copyIcon}
              onClick={() => {
                copyHandler(amazonInfo?.dynamicSignTime)
              }}
            />
          </div>
          <div className={styles.item}>
            <span className={styles.label}>实际签收日期</span>
            <span>{amazonInfo?.practicalSignTime}</span>
            <Popover
              overlayInnerStyle={{ width: '400px' }}
              open={actualSignFlag}
              trigger="click"
              destroyTooltipOnHide={true}
              content={
                <div>
                  <div className={styles.flex}>
                    <span>实际签收日期</span>
                    <DatePicker
                      style={{ flex: '1 auto' }}
                      defaultValue={
                        infoRef.current.practicalSignTime ? dayjs(infoRef.current.practicalSignTime) : undefined
                      }
                      onChange={value => {
                        infoRef.current.practicalSignTime = dayjs(value).format($F_YMD)
                      }}
                    />
                  </div>
                  <div className={styles.footer}>
                    <Button
                      onClick={() => {
                        setActualSignFlag(false)
                        infoRef.current = amazonInfo
                      }}
                    >
                      取消
                    </Button>
                    <Button
                      type="primary"
                      onClick={() => {
                        onSaveHandler('practicalSignTime')
                      }}
                    >
                      保存
                    </Button>
                  </div>
                </div>
              }
            >
              <EditOutlined
                className={styles.editIcon}
                onClick={() => {
                  setActualSignFlag(true)
                }}
              />
            </Popover>
          </div>
        </div>
      </div>
    </Card>
  )
}
